package logic

import (
	"api/pkg"
	"context"
	"net/http"
	"path/filepath"
	"time"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type HandlerUploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewHandlerUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HandlerUploadLogic {
	return &HandlerUploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *HandlerUploadLogic) HandlerUpload(req *http.Request) (resp *types.Response, err error) {

	file, m, err := req.FormFile("img")
	if err != nil {
		return &types.Response{
			Msg:  "视频获取失败",
			Code: "500",
			Data: nil,
		}, nil
	}
	if m.Size > 5*1024*1024 {
		return &types.Response{
			Msg:  "视频过大",
			Code: "500",
			Data: nil,
		}, nil
	}
	ext := filepath.Ext(m.Filename)
	video := map[string]bool{
		".mp4": true,
		".png": true,
		".jpg": true,
	}
	if !video[ext] {
		return &types.Response{
			Msg:  "视频格式不支持",
			Code: "500",
			Data: nil,
		}, nil
	}
	filename := time.Now().Format("20060102150405") + ext
	yun, err := pkg.QiNiuYun(file, filename)
	if err != nil {
		return &types.Response{
			Msg:  "视频上传失败",
			Code: "500",
			Data: nil,
		}, nil
	}
	return &types.Response{
		Msg:  "视频上传成功",
		Code: "200",
		Data: map[string]interface{}{
			"video": yun,
		},
	}, nil
}
